const gulp = require('gulp');
const config = require('./config');
const path = require('path');


const browserify = require('browserify');
const watchify = require('watchify');
const babelify = require('babelify');
const source = require('vinyl-source-stream');
const buffer = require('vinyl-buffer');
const merge = require('utils-merge');
const gutil = require('gulp-util');
const chalk = require('chalk');
const babel = require('gulp-babel');
const watch = require('node-watch')
const sourcemaps = require('gulp-sourcemaps');
const exec = require('child_process').exec;

var obj =  require.cache[Object.keys(require.cache)
    .find((x) => x.indexOf('gulp-util/index') >= 0)];

if (obj && obj.exports) {
    obj.exports.colors.stripColor = require('strip-ansi');
}


function map_error(err) {
    if (err.fileName) {
        // regular error
        gutil.log(chalk.red(err.name)
            + ': '
            + chalk.yellow(err.fileName.replace(__dirname + '/src/js/', ''))
            + ': '
            + 'Line '
            + chalk.magenta(err.lineNumber)
            + ' & '
            + 'Column '
            + chalk.magenta(err.columnNumber || err.column)
            + ': '
            + chalk.blue(err.description))
    } else {
        // browserify error..
        gutil.log(chalk.red(err.name)
            + ': '
            + chalk.yellow(err.message))
    }

    this.end()
}

var file = config.espath;
var fileoptions = {
    presets: [
        ["es2015", {
            loose: true
        }]
    ],
    plugins: [
        ["transform-class-properties", { "spec": true }],
        "transform-custom-element-classes",
        ["transform-object-rest-spread", { "useBuiltIns": true }],
        "transform-es3-property-literals",
        "transform-es3-member-expression-literals"
    ]
};

let defaultscriptoption = {
    debug: true
};

let scriptcompileoption = Object.assign(defaultscriptoption, config.compileoptions);

gulp.task('script:watch', function () {
    var args = merge(watchify.args, scriptcompileoption)
    var bundler = watchify(browserify(file, args))
        .transform(babelify, fileoptions)

    console.log("build file mjs");

    bundle_js(bundler);

    bundler.on('update', function () {
        bundle_js(bundler)
    })
});

function bundle_js(bundler, dest = config.destroot) {
    let ret = bundler.bundle()
        .on('error', map_error)
        .pipe(source(`index.js`))
        .pipe(buffer())
        .pipe( gulp.dest(dest) )

    if (config.sourcemaps) {
        return ret.pipe(sourcemaps.init({ loadMaps: true }))
            .pipe(sourcemaps.write(dest))
            .pipe(gulp.dest(config.jspath))
    } else {
        return ret;
    }
}

gulp.task('script', function () {
    let bundler = browserify(file, scriptcompileoption)
        .transform(babelify, fileoptions);

    return bundle_js(bundler)
});

gulp.task('lib', function () {
    gulp.src("src/**/*.js")
        .pipe(babel(fileoptions))
        .pipe(gulp.dest(config.dlibroot))
});

// watch(path.join(__dirname, "webcomponents"), { recursive: true }, function(evt, src) {
//     let paths = src.split(path.sep);
//     console.log(src);
//     if (src.endsWith("mjs") && src.indexOf("___jb_") < 0) {
//         gulp.src(src)
//             .pipe(babel({
//                 presets: ['env']
//             }))
//             .pipe(gulp.dest(path.dirname(src)))
//     }
// });

